﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECRMS.Biz.Dom;
using ECRMS.Data;
using System.Web;
using System.Web.Security;

namespace ECRMS.Biz
{
    public class EcUserLogic
    {
        public bool TryLogin(string username, string password)
        {
            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                var login = dataContext.GetTable<ECLogin>()
                    .FirstOrDefault(q => q.Username == username && q.Password == password);

                if (login == null)
                    return false;

                FormsAuthentication.SetAuthCookie(login.UserRefId.ToString(), false);

                return true;
            }
        }

        public void Logout()
        {
            FormsAuthentication.SignOut();
        }

        public bool ChangePassword(string oldPwd, string newPwd, string confirmPwd)
        {
            if (newPwd != confirmPwd)
                return false;

            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                var userRefId = new Guid(HttpContext.Current.User.Identity.Name);
                var login = dataContext.GetTable<ECLogin>()
                    .FirstOrDefault(q => q.UserRefId == userRefId && q.Password == oldPwd);

                if (login == null)
                    return false;

                login.Password = newPwd;

                dataContext.SubmitChanges();

                return true;
            }
        }

        public List<Employer> GetEmployers(Guid corporationRefId)
        {

            return null;
        }

        public List<EcUser> GetUsers()
        {
            using (var dataContext = ECRMSDataContext.NewInstance())
            {
                return (from usr in dataContext.GetTable<ECLogin>()
                        where !usr.IsDisabled
                        select new EcUser
                        {
                            UserRefId = usr.UserRefId,
                            Gender = usr.Gender,
                            UserTypeId = usr.UserTypeId,
                            Email = usr.Email,
                            Name = usr.Name
                        }).ToList();
            }
        }
    }
}
